import { Router } from 'vue-router';
import { permissionStore } from '/@/store/modules/permission';
import { PageEnum } from '/@/enums/pageEnum';
import { getToken } from '/@/utils/auth/index';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/constant';
const LOGIN_PATH = PageEnum.BASE_LOAGIN;

const whitePathList: PageEnum[] = [LOGIN_PATH];

export function createPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    // 从登录页面进来 目标页为错误页跳首页
    if (from.path === PageEnum.BASE_LOAGIN && to.name === PAGE_NOT_FOUND_ROUTE.name) {
      next(PageEnum.BASE_HOME);
      return;
    }

    // 过滤白名单
    if (whitePathList.includes(to.path as PageEnum)) {
      next();
      return;
    }

    const token = getToken();

    // token拦截
    if (!token) {
      // meta中是否有免验证标识
      if (to.meta.ignoreAuth) {
        next();
        return;
      }

      const redirectData = { path: LOGIN_PATH, replace: true, query: {} };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }

      next(redirectData);
      return;
    }

    // 如果路由已经添加直接执行
    if (permissionStore.getIsDynamicAddedRouteState) {
      next();
      return;
    }

    const routes = await permissionStore.buildRoutesAction();
    routes.forEach((route) => {
      router.addRoute(route);
    });

    const redirectPath = (from.query.redirect || to.path) as string;
    const redirect = decodeURIComponent(redirectPath);
    const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
    permissionStore.commitDynamicAddedRouteState(true);
    next(nextData);
  });
}
